package controllers

import (
	"read.com/admin/models"
	"github.com/astaxie/beego/orm"
)

type HomepageController struct {
	BaseController
}

type FormatConfigTopic struct {
	Sort        int
	ChannelType int8
	TopicType   int8
	BookId      int
	BookName    string
	SortId      int
}

func (self *HomepageController) List() {
	self.Data["pageTitle"] = "配置表"
	self.display()
}

func (self *HomepageController) Table() {
	channel, _ := self.GetInt8("channel")
	topic, _ := self.GetInt8("topic")

	cond := orm.NewCondition()
	//列表参数
	page, err := self.GetInt("page")
	if err != nil {
		page = 1
	}
	limit, err := self.GetInt("limit")
	if err != nil {
		limit = 10
	}
	cond = cond.And("topic_type", topic).And("channel_type", channel)

	allTopList, total := models.GetConfigTopic(page, limit, cond)

	result := make([]*FormatConfigTopic, 0)
	for k, v := range allTopList {
		formatConfigTopic := &FormatConfigTopic{
			Sort:        k + 1,
			ChannelType: v.ChannelType,
			TopicType:   v.TopicType,
			SortId:      v.SortId,
			BookName:    models.GetBookByID(v.BookId).Name,
			BookId:      v.BookId,
		}
		result = append(result, formatConfigTopic)
	}
	self.ajaxList("成功", MSG_OK, total, result)
}

func (self *HomepageController) Add() {
	bookId, _ := self.GetInt("id")
	channel, _ := self.GetInt8("channel")
	topic, _ := self.GetInt8("topic")
	err := models.AddConfigTopic(bookId, channel, topic)
	if err != nil {
		self.ajaxMsg("新增失败", MSG_ERR)
	} else {
		self.ajaxMsg("新增成功", MSG_OK)
	}
}

func (self *HomepageController) Edit() {
	bookId, _ := self.GetInt("id")
	channel, _ := self.GetInt8("channel")
	topic, _ := self.GetInt8("topic")
	sortId, _ := self.GetInt("sortId")

	err := models.UpdateConfigTopic(bookId, channel, topic, sortId)
	if err != nil {
		self.ajaxMsg("编辑失败", MSG_ERR)
	} else {
		self.ajaxMsg("编辑成功", MSG_OK)
	}
}

func (self *HomepageController) Del() {
	bookId, _ := self.GetInt("bookId")
	channel, _ := self.GetInt8("channel")
	topic, _ := self.GetInt8("topic")
	sortId, _ := self.GetInt("sortId")

	err := models.DelConfigTopic(bookId, channel, topic, sortId)
	if err != nil {
		self.ajaxMsg("删除失败", MSG_ERR)
	} else {
		self.ajaxMsg("删除成功", MSG_OK)
	}
}

func (self *HomepageController) Empty() {
	channel, _ := self.GetInt8("channel")
	topic, _ := self.GetInt8("topic")

	err := models.EmptyConfigTopic(channel, topic)
	if err != nil {
		self.ajaxMsg("删除失败", MSG_ERR)
	} else {
		self.ajaxMsg("删除成功", MSG_OK)
	}
}
